package com.yvtian.utils;

import com.yvtian.admin.vo.TreeVO;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class TreeUtils {

    public static List<TreeVO> convertToTree(List<TreeVO> treeList) {
        Map<Integer, TreeVO> treeMap = treeList.stream().collect(Collectors.toMap(TreeVO::getId, Function.identity()));
        List<TreeVO> treeStructure = new ArrayList<>();

        for (TreeVO node : treeList) {
            if (node.getParentId() != -1) {
                TreeVO parent = treeMap.get(node.getParentId());
                if (parent != null) {
                    if (parent.getTreeVOS() == null) {
                        parent.setTreeVOS(new ArrayList<>());
                    }
                    parent.getTreeVOS().add(node);
                } else {
                    // 父节点为空
                }
            } else {
                treeStructure.add(node);
            }
        }

        return treeStructure;
    }

}
